#include "PrePackage.h"
PrePackage::PrePackage(PackagerUI *pUI, QString DirPath, QObject *parent) : QObject(parent)
{
    if(pUI==NULL||DirPath.isEmpty()){
        qWarning()<<"Input parameter DirPath in PrePackage::initDirPath can not be null."<<endl;
        emit pUI->sendStateInfo(tr("Input parameter DirPath in PrePackage::initDirPath can not be null."));
        return ;
    }
    this->mDirPath = DirPath;
    this->mUI = pUI;
    mDataUtil = new DataUtil();
}

bool PrePackage::initDirPath(){
    if(!PathUtil::makeDirs(mDirPath+"/java",true)) return false;
    if(!PathUtil::makeDirs(mDirPath+"/wrapper",true)) return false;
    if(!PathUtil::makeDirs(mDirPath+"/wrapper/model",true)) return false;
    if(!PathUtil::makeDirs(mDirPath+"/wrapper/supportive",true)) return false;
    if(!PathUtil::makeDirs(mDirPath+"/wrapper/testify",true)) return false;
    return true;

  }

bool PrePackage::PreConversionMethods(const QMap<int, DCCInfo *> *DCCInfoMap){

    if(mDCCInfoMap==NULL){
     qWarning()<<"Input parameter mDCCInfo in PrePackage::PreConversionMethods can not be null."<<endl;
     emit mUI->sendStateInfo(tr("Input parameter mDCCInfo in PrePackage::PreConversionMethods can not be null."));
     return false;
    }
    this->mDCCInfoMap = DCCInfoMap;
        for(int i=0;i<mDCCInfoMap->size();i++){
                QString MethodFold  = mDCCInfoMap->value(i)->getMethodFold();
                if(MethodFold.isEmpty()){
                    qWarning()<<"Method fold is null in PrePackage::PreConversionMethods."<<endl;
                    emit mUI->sendStateInfo(tr("Method fold is null in PrePackage::PreConversionMethods."));
                    return false;
                }
                if(!QDir(MethodFold).exists()){
                    qWarning()<<"have no this method :"<<MethodFold<<" ."<<endl;
                    return false;
                }
                if(!copyDirFiles(MethodFold,this->mDirPath+"/wrapper/model/"+QDir(MethodFold).dirName(),true)){
                    qWarning()<<"copy Method fold error : "<<MethodFold<<" ."<<endl;
                    return false;
                }
        }
        return true;
}

bool PrePackage::PreMdl(QString MdlFilePath){
    if(MdlFilePath==NULL||MdlFilePath.isEmpty()){
        qWarning()<<"Input parameter MdlFilePath in PrePackage::PreMdl can not be null."<<endl;
        return false;
    }
    if(QFileInfo(QFile(MdlFilePath)).isFile()){
        if(!copyFileToPath(MdlFilePath,this->mDirPath+"/wrapper/model/"+QDir(MdlFilePath).dirName(),true)){
            qWarning()<<"copy mdl file error in PrePackage::PreMdl."<<endl;
            return false;
        }
    }else{
        qWarning()<<"Are you sure the mdl file  which you choose is a file?"<<endl;
        emit sendStateInfo(tr("Are you sure the mdl file  which you choose is a file?"));
        return false;
    }
    //modify mdl file
      QMap<QString,QList<QString>*> *InsertMap=new QMap<QString,QList<QString>* >();

    //libList
      InsertMap->insert("LibraryConfigures",mDataUtil->getAllTableData(mUI->LibNamesTable));
    //HardConTable
      InsertMap->insert("HardwareConfigures",mDataUtil->getAllTableData(mUI->HardConTable));
    //SoftEnvirTable
      InsertMap->insert("SoftwareConfigures",mDataUtil->getAllTableData(mUI->SoftEnvirTable));
    //SuportResList
      InsertMap->insert("SupportConfigures",mDataUtil->getAllTableData(mUI->SuportResList));
    if(!get_setInfo::addMdlNode(this->mDirPath+"/wrapper/model/"+QDir(MdlFilePath).dirName(),InsertMap)){
        qWarning()<<"mdl file add node error in PrePackage::PreMdl."<<endl;
        return false;
    }
    this->mCurrentMdlPath = MdlFilePath;
    return true;
}

bool PrePackage::PreFilesInTable(){
    if(mUI==NULL){
        qWarning()<<"input parameter pUI in PrePackage::PreFilesInTable can not be null."<<endl;
        return false;
    }
    //model lib
    if(!mDataUtil->copySpecialFile(mUI->LibNamesTable,this->mDirPath+"/wrapper/model")) {
        qWarning()<<"copy model lib error in PrePackage::PreFilesInTable."<<endl;
        return false;
      }
    //test data
    if(!mDataUtil->copySpecialFile(mUI->TestDataList,this->mDirPath+"/wrapper/testify")) {
        qWarning()<<"copy test data error in PrePackage::PreFilesInTable."<<endl;
        return false;
      }
    //supportive resource
    if(!mDataUtil->copySpecialFile(mUI->SuportResList,this->mDirPath+"/wrapper/supportive")) {
        qWarning()<<"copy supportive resource error in PrePackage::PreFilesInTable."<<endl;
        return false;
      }
    return true;
}

bool PrePackage::PreProject(QString FilePath,QString ProjectRelativePath){
    if(FilePath==NULL || FilePath.isEmpty()||ProjectRelativePath==NULL||ProjectRelativePath.isEmpty()){
        qWarning()<<"The input parameter FilePath in PrePackage::PreProject can not be null."<<endl;
        emit sendStateInfo(tr("you must choose EXE file."));
        return false;
    }
    QString ModelPath = mDirPath+"/wrapper/model/";
    QString ExeSrcPath = mUI->ProjectPath->text();
    QString ExeDesPath = PathUtil::RelativePathToAbsolutePath(ModelPath,ProjectRelativePath);
    if(QFileInfo(QFile(FilePath)).isFile()){
            if(!copyFileToPath(ExeSrcPath,ExeDesPath,true)){
                qWarning()<<"Copy file"<<ExeSrcPath<<"in PrePackage::PreProject error."<<endl;
                return false;
            }
    }else{
        if(!copyDirFiles(ExeSrcPath,ExeDesPath,true)){
            qWarning()<<"Copy file"<<ExeSrcPath<<"in PrePackage::PreProject error."<<endl;
            return false;
        }
    }
    return true;
}

bool PrePackage::PreLicense(){
     QString LicenseContent= mUI->LicenseTextArea->toPlainText();
    if(LicenseContent.isEmpty()){
        qWarning()<<"license content is  null."<<endl;
        return false;
    }
    if(!SaveFile(mDirPath+"/wrapper/license.txt",LicenseContent)){
        qWarning()<<"license prepare error."<<endl;
        return false;
    }
    return true;
}

bool PrePackage::PrePackageConfig(QString Host,
                                  QString Port,
                                  QString Type,
                                  QString JarRelativePath,
                                  QString MdlRelativePath,
                                  QString TestDataStr){

    if(Host.isEmpty()){
        qWarning()<<"input parameter Host in PrePackage::PrePackageConfig is empty."<<endl;
        return false;
    }
    if(Port.isEmpty()){
        qWarning()<<"input parameter Port in PrePackage::PrePackageConfig is empty."<<endl;
        return false;
    }
    if(Type.isEmpty()){
        qWarning()<<"input parameter Type in PrePackage::PrePackageConfig is empty."<<endl;
        return false;
    }
    if(JarRelativePath.isEmpty()){
        qWarning()<<"input parameter JarRelativePath in PrePackage::PrePackageConfig is empty."<<endl;
        return false;
    }
    if(MdlRelativePath.isEmpty()){
        qWarning()<<"input parameter MdlRelativePath in PrePackage::PrePackageConfig is empty."<<endl;
        return false;
    }
    if(TestDataStr.isEmpty()){
        qWarning()<<"input parameter TestDataStr in PrePackage::PrePackageConfig is empty."<<endl;
       // return false;
    }
    QString PackageCOnfig = "";
    PackageCOnfig += "host "+Host+"\n";
    PackageCOnfig += "port "+Port+"\n";
    PackageCOnfig += "type "+Type+"\n";
    PackageCOnfig += "start "+JarRelativePath+"\n";
    PackageCOnfig += "mdl "+MdlRelativePath+"\n";
    PackageCOnfig += "testdata "+TestDataStr+"\n";
    PackageCOnfig += "engine >=0.0.1\n";

    if(!SaveFile(mDirPath+"/wrapper/package.config",PackageCOnfig)){
        qWarning()<<"Save package.config error in PrePackage::PrePackageConfig."<<endl;
        return false;
    }
    return true;
}


bool PrePackage::PreModelRunLib(){
    if(!copyDirFiles(this->mDirPath+"/templates/ModelRunLib",this->mDirPath+"/wrapper/model",true)){
        qWarning()<<"copy ModelRunLib error in  PrePackage::PreModelRunLib."<<endl;
        return false;
    }
    return true;
}


bool PrePackage::PreJar(QString jarName){

    //prepare Main
    CodeHandle *mCodeHandle = new CodeHandle();
    mCodeHandle->init(this->mDirPath+"\\templates\\java\\Main.java");
    mCodeHandle->setMdlName(QDir(this->mCurrentMdlPath).dirName());
    mCodeHandle->setInputParameter(mUI->ModelInputParameter->text());
    mCodeHandle->setModelRelativeLocation(mUI->ProjectRelativePath->text());

    mCodeHandle->beginAddResEvent();
    mCodeHandle->beginAddNoResEvent();
    for(int i=0;i<this->mDCCInfoMap->size();i++){
        DCCInfo *mDCCInfo = this->mDCCInfoMap->value(i);
        QString MethodRelativePath = "./"+mDCCInfo->getInternalMethodName()+"/"+mDCCInfo->getInternalMethodName()+".exe";
        if(mDCCInfo->getEventType()=="response"){
            if(!mCodeHandle->addResEvent(mDCCInfo->getEventName(),MethodRelativePath,mDCCInfo->getFileRelativePath())){
                qWarning()<<"Add resEvent error."<<endl;
                return false;
            }
        }else if(mDCCInfo->getEventType()=="noresponse"){
            if(!mCodeHandle->addNoResEvent(mDCCInfo->getEventName(),MethodRelativePath,mDCCInfo->getFileRelativePath())){
                qWarning()<<"Add NoResEvent error."<<endl;
                return false;
            }

        }
    }
    mCodeHandle->endAddResEvent();
    mCodeHandle->endAddNoResEvent();

    if(!mCodeHandle->SaveMainFile(this->mDirPath+"/java/main/Main.java")){
        qWarning()<<"Save MainFile error."<<endl;
        return false;
    }

    //Prepare Manifest.MF

    if(!copyFileToPath(this->mDirPath+"\\templates\\java\\MANIFEST.MF",this->mDirPath+"/java/MANIFEST.MF",true)){
        qWarning()<<"copy MANIFEST.MF error."<<endl;
        return false;
    }

    //Prepare compile.bat

    QFile CompileFile(this->mDirPath+"\\templates\\java\\compile.bat");
    if(!CompileFile.exists()){
        qWarning()<<"Compile File does not exist."<<endl;
        return false;
    }
    if(!CompileFile.open(QIODevice::ReadWrite | QIODevice::Text)){
        qWarning()<<"Failed to open template  compile.bat."<<endl;
        return false;
    }
    QString CompileFileStr(CompileFile.readAll());
    CompileFile.close();

    if(!CompileFileStr.isEmpty()){
        QString ProjectPath =this->mDirPath;
        ProjectPath.replace("/","\\");
        CompileFileStr.replace("${ProjectPath}",ProjectPath);
        CompileFileStr.replace("${ModelName}",jarName);
         if(!SaveFile(this->mDirPath+"/java/compile.bat",CompileFileStr)){
             qWarning()<<"Save compile error."<<endl;
             return false;
         }
    }else{
        qWarning()<<"the content of template compile.bat is null."<<endl;
        return false;
    }

    //compile
        if(!CmdProcess::RunCmd(this->mDirPath+"\\java\\compile.bat")){
            qWarning()<<"Run cmd error."<<endl;
            return false;
        }


    return true;
}

bool PrePackage::PreZip(QString mFileName){
    QString fileName = mFileName;
    if(!fileName.isEmpty()){
        QString winRARPath = "\""+this->mDirPath+"\\templates\\winrar\\WinRAR.exe"+"\"";
        QString ZipPath = "\""+fileName+"\"";
        QString SrcFoldPath = "\""+this->mDirPath+"\\wrapper\\"+"\"";
        QString commandStr = (winRARPath+" a -ep1 -r -m3 -ibck "+ZipPath+" "+SrcFoldPath);

        if(!CmdProcess::RunCmd(commandStr)){
            qWarning()<<"Run cmd error in PreZip."<<endl;
            mUI->GeneratePackage->setEnabled(true);
            return false;
        }
    }
    //删除临时文件，临时文件夹
    if(DelDir(this->mDirPath+"/javaTemp")&& DelDir(this->mDirPath+"/java")&& DelDir(this->mDirPath+"/wrapper")){
    }else{
        qWarning()<<"Failed to delete the fold."<<endl;
    }
      mUI->GeneratePackage->setEnabled(true);
      return true;

}





